//
// Created by francklinson on 2021/5/14.
//
#include <string>
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

class Solution {
public:
    string removeDuplicates(string s, int k) {
        string stack;
        vector<pair<char, int>> record;
        for (auto x:s) {
            if (stack.empty() or x != stack.back()) {
                stack.push_back(x);
                record.emplace_back(x, 1);
            } else {
                stack.push_back(x);
                record.back().second++;
                if (record.back().second == k) {
//                    for (int i = 0; i < k; ++i)stack.pop_back();
                    stack.erase(stack.end()-k,stack.end());
                    record.pop_back();
                }
            }
        }
        return stack;
    }
    string removeDuplicates2(string s, int k) {
        stack<int> counts;
        for (int i = 0; i < s.size(); ++i) {
            if (i == 0 || s[i] != s[i - 1]) {
                counts.push(1);
            } else if (++counts.top() == k) {
                counts.pop();
                s.erase(i - k + 1, k);
                i = i - k;
            }
        }
        return s;
    }

};


int main() {
    Solution sol;
    cout << sol.removeDuplicates2("abcd", 2) << endl;
    cout << sol.removeDuplicates("deeedbbcccbdaa", 3) << endl;
    cout << sol.removeDuplicates("pbbcggttciiippooaais", 2) << endl;
    return 0;
}